<?php

namespace app\api\controller\yexam;

use app\common\controller\Api;
use app\common\model\Category as CategoryModel;
use fast\Tree;

/**
 * @ApiSector (分类接口)
 * @ApiInternal
 */
class Category extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     */
    public function index()
    {
	    $this->model = model('app\common\model\Category');
        $this->subject = model('app\admin\model\yexam\Subject');
        $tree = Tree::instance();
        $tree->init(collection($this->model->field('id,pid,name,type,flag')->where('type', 'exam')->order('weigh asc,id asc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $subject_group = collection($this->subject->field('category_id, count(id) as subject_count')->group('category_id')->select())->toArray();
        $category_subject_count = array_column($subject_group, 'subject_count', 'category_id');
        $categorydata = [];
        // 最多支持三级显示
        $pre_key = null;
        $sec_key = null;
        foreach ($this->categorylist as $k => &$v) {
            $v['name'] = trim(str_replace($v['spacer'], '', $v['name']));
            
            if ($v['pid'] == 0) {
                $pre_key = $k;

                // 一级
                $pre_category_id = $v['id'];
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key] = $v;
            } else if ($v['pid'] == $pre_category_id) {
                $sec_key = $k;

                // 二级
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key]['childs'][$sec_key] = $v;;
            } else {
                // 三级
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key]['childs'][$sec_key]['childs'][] = $v;;
            }
        }
        $this->success('请求成功', $categorydata);
    }
    /**
     * 通过分类id返回下级分类
     */
    public function getNextCategory(){
        $id = $this->request->param('category_id');
        $category = model('app\common\model\Category');
        $list = $category->where('pid',$id)->select();
        $this->success('请求成功',$list);
    }
}
